package com.ptswitch.material.pages.bom;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.hxzon.project.AppRuntimeException;
import org.slf4j.Logger;
import org.springframework.dao.DataAccessException;

import com.ptswitch.material.model.material.Bom;
import com.ptswitch.material.model.material.BomOrigFile;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.BomService;
import com.ptswitch.material.service.MaterialExcelService;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.WebUtil;
import com.ptswitch.material.util.security.PermissionUtil;

public class ImportBom extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private MaterialExcelService excelSer;
    @Inject
    private BomService bomSer;
    @Property
    private Bom bom;
    @Property
    private UploadedFile file;
    @InjectPage
    private ViewBom viewBom;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init() {
        checkPermitted(PermissionUtil.BomCreate);
        bom = new Bom();
        return null;
    }

//	@OnEvent(value=EventConstants.VALIDATE_FORM,component="import")
//	Object validate(){
//		mustAdmins();
//		
//		return null;
//	}

    @OnEvent(value = EventConstants.SUCCESS, component = "import")
    Object importBom() {
        checkPermitted(PermissionUtil.BomCreate);
        //check exist
        Bom dbBom = bomSer.findByCodeAndVersion(bom.getCode(), bom.getVersion());
        if (dbBom != null) {
//			setMessage("新增单板表失败：已存在同名同版本号的单板表，请点击修改。");
            throw AppRuntimeException.error("新增单板表失败：已存在同名同版本号的单板表，请点击修改。");
        }
        //excel
        BomOrigFile upload = WebUtil.upload(file, BomOrigFile.class);
        try {
            excelSer.buildBomFromExcel(bom, WebUtil.getRealFilePath(upload));
        } catch (Throwable e) {
            WebUtil.delete(upload);
            throw AppRuntimeException.rethrow("读取单板表文件错误", e);
        }
        // db
        try {
            upload.setUser(getVisitor());
            bom.setOrigFile(upload);
            bom.setFileName(upload.getFilePath());
            bomSer.saveEx(bom);
            hlog(HlogConstants.addBom, bom);
            return viewBom.withInit(bom.getId());
        } catch (Throwable e) {
            if (e instanceof DataAccessException) {
                e = e.getCause().getCause();
            }
            throw AppRuntimeException.rethrow("导入单板表错误", e);
        }
    }
}
